package com.frain.springcloud.tuling.util;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.frain.springcloud.tuling.entity.InputTextPerception;
import com.frain.springcloud.tuling.entity.PerceptionObject;
import com.frain.springcloud.tuling.entity.Result;
import com.frain.springcloud.tuling.entity.TuLingRequestEntity;
import com.frain.springcloud.tuling.entity.TuLingResponseEntity;
import com.frain.springcloud.tuling.entity.UserInfo;
import com.frain.springcloud.util.Collections3;
import com.frain.springcloud.util.HttpRequest;

/**
 * 
 * @ClassName: TulingUtil 
 * @Description: 图灵返回聊天机器人
 * @author frain
 * @date 2018年9月4日 下午7:45:41 
 *
 */
public class TulingUtil {

    private static String path = "http://openapi.tuling123.com/openapi/api/v2";

    public static String sendText(String context) {

        TuLingRequestEntity request = createRequestEntity(context);

        try {
            TuLingResponseEntity response = sendPost(request);
            if (response != null && !Collections3.isEmpty(response.getResults())) {

                Result first = Collections3.getFirst(response.getResults());
                if (first.getResultType().equals("text")) {
                    return first.getValues().getText();
                }

                if (first.getResultType().equals("url")) {
                    return first.getValues().getUrl();
                }

            }

            return "";
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return "";

    }

    private static TuLingResponseEntity sendPost(TuLingRequestEntity request) {

        if (request != null) {
            try {
                String post = HttpRequest.sendPost(path, JSONObject.toJSONString(request), null);
                if (StringUtils.isNoneBlank(post)) return JSONObject.parseObject(post, TuLingResponseEntity.class);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private static TuLingRequestEntity createRequestEntity(String context) {
        TuLingRequestEntity request = new TuLingRequestEntity();

        request.setReqType(0);
        request.setUserInfo(new UserInfo());

        PerceptionObject perception = new PerceptionObject();
        InputTextPerception inputText = new InputTextPerception();
        inputText.setText(context);
        perception.setInputText(inputText);
        request.setPerception(perception);
        return request;
    }

    public static void main(String[] args) {

        String sendText = sendText("笑话");
        if (StringUtils.isNoneBlank(sendText)) {

            System.out.println(sendText);
        }

    }

}
